package top.lingkang.finaloauth.server.controller;

import cn.hutool.core.lang.Assert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import top.lingkang.finaloauth.entity.OauthUser;
import top.lingkang.finaloauth.server.base.OauthUserLoginHandler;
import top.lingkang.finaloauth.server.config.OauthServerConfig;
import top.lingkang.finaloauth.server.error.ServerException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author lingkang
 * Created by 2022/3/16
 */
@RestController
public class FinalAuthServer {

    @Autowired
    private HttpServletRequest request;
    @Autowired
    private OauthUserLoginHandler oauthUserLoginHandler;

    private OauthServerConfig configuration;

    public FinalAuthServer(OauthServerConfig configuration) {
        this.configuration = configuration;
    }

    @PostMapping("/oauth/token")
    public Object token(String username, String password, String client_id, String grant_type, String client_secret,
                        String redirect_url, HttpServletResponse response) throws Exception {
        Assert.notNull(grant_type, "grant_type not null");
        if ("password".equals(password)) {
            password(request, response);
        }

        return null;
    }

    private void password(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String client_id = request.getParameter("client_id");
        Assert.notNull(client_id, "client_id not null");
        String client_secret = request.getParameter("client_secret");
        Assert.notNull(client_secret, "client_secret not null");


        OauthUser handler = oauthUserLoginHandler.handler(
                request.getParameter(configuration.getLoginUsername()),
                request.getParameter(configuration.getLoginUsername()),
                request
        );
        if (handler==null){
            throw new ServerException("account not exists or password error. 账户不存在或密码错误！");
        }


    }
}
